package org.example;

public class ListNode {

    public int val;
    public ListNode next;
    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    // 构造函数
    public ListNode(int val) {
        this.val = val;
        this.next = null;
    }


    // 方法来构建链表
    public static ListNode of(int... values) {
        if (values == null || values.length == 0) {
            return null;
        }
        ListNode head = new ListNode(values[0]); // 创建头节点
        ListNode current = head; // 当前节点指针
        for (int i = 1; i < values.length; i++) {
            current.next = new ListNode(values[i]); // 创建新节点并链接到当前节点
            current = current.next; // 移动到下一个节点
        }
        return head; // 返回头节点
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        ListNode current = this;
        while (current != null) {
            sb.append(current.val);
            sb.append("->");
            current = current.next;
        }
        return sb.toString();
    }
}
